package end.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.comet4j.core.CometContext;
import org.comet4j.core.CometEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.ObjectMapper;

import redis.clients.jedis.Jedis;
import end.bean.Announcement;
import end.bean.shiro.Manager;
import end.constant.Const;
import end.ser.AnnouncementSER;
import end.util.DateUtils;
import end.util.jedis.JedisPoolUtils;

/**
 * 
 * ChapterForController.java 2016-6-29
 * 
 * Copyright zhaocj Inc. All rights reserved. Love Me Like Love Justin Bieber
 */
@Controller
@RequestMapping("/home/")
public class HomePageForController {
	private final static Logger logger = LogManager
			.getLogger(AlbumForController.class);
	private ObjectMapper mapper = new ObjectMapper();
	@Autowired
	private AnnouncementSER<Announcement> announcementSER;

	public AnnouncementSER<Announcement> getAnnouncementSER() {
		return announcementSER;
	}

	public void setAnnouncementSER(AnnouncementSER<Announcement> announcementSER) {
		this.announcementSER = announcementSER;
	}

	@RequestMapping("currentManagers")
	public @ResponseBody
	List<Manager> listCurrentManagers() throws Exception {
		mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
		Jedis jedis = JedisPoolUtils.getJedis();
		jedis.select(6);
		List<String> lrange = jedis.lrange(Const.CURRENT_LOGIN_MANAGERS, 0, 4);
		List<Manager> managers = new ArrayList<Manager>();
		for (String string : lrange) {
			managers.add(mapper.readValue(string, Manager.class));
		}
		JedisPoolUtils.close(jedis);
		return managers;
	}

	@RequestMapping("listAnnouncementByManager")
	public @ResponseBody
	List<Announcement> listAnnouncementByManager() throws Exception {
		return announcementSER.listAnnouncementByManager();
	}

	@RequestMapping("testComet")
	public @ResponseBody
	boolean testComet() throws Exception {
		CometEngine engine = CometContext.getInstance().getEngine();
		engine.sendToAll(Const.COMET_CHANNEL_ANNOUNCES_STATUS,
				DateUtils.getDate("yyyy/MM/dd HH:mm:ss"));
		engine.sendToAll(Const.COMET_CHANNEL_SERVER_FLAG, "1");
		return true;
	}
}
